package com.lambada.test1;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ListSortTest {


    public static void main(String[] args) {

    }


    /**
     * 数字排序
     */
    public static void testIntegerSort() {
        List<Integer> list = Arrays.asList(4, 2, 5, 3, 1);
        System.out.println(list);//执行结果：[4, 2, 5, 3, 1]




        //升序
        list.sort((a, b) -> a.compareTo(b.intValue()));
        System.out.println(list);//执行结果：[1, 2, 3, 4, 5]
        //降序
        list.sort((a, b) -> b.compareTo(a.intValue()));
        System.out.println(list);//执行结果：[5, 4, 3, 2, 1]
    }

    /**
     * 对象串排序
     */
    public void testObjectSort() {
        List<Person> list = new ArrayList<>();
        list.add(new Person("三炮", 48));
        list.add(new Person("老王", 35));
        list.add(new Person("小明", 8));
        list.add(new Person("叫兽", 70));
        System.out.println(list); //执行结果：[Person{name='三炮', age=48}, Person{name='老王', age=35}, Person{name='小明', age=8}, Person{name='叫兽', age=70}]
        //按年龄升序
        list.sort((a, b) -> Integer.compare(a.getAge(), b.getAge()));
        System.out.println(list);//执行结果：[Person{name='小明', age=8}, Person{name='老王', age=35}, Person{name='三炮', age=48}, Person{name='叫兽', age=70}]

        //按年龄降序
        list.sort((a, b) -> Integer.compare(b.getAge(), a.getAge()));
        System.out.println(list);//执行结果：[Person{name='叫兽', age=70}, Person{name='三炮', age=48}, Person{name='老王', age=35}, Person{name='小明', age=8}]
        //如果按姓名排序，其实就是按字符串排序一样
    }

}
